package thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;


/**
 * @Author: Administrator
 * @Date: 2023/2/14 16:48
 */

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {

//        testFirstAwait();

        testFirstCount();
    }

    private static void testFirstCount() throws InterruptedException {

        CountDownLatch countDownLatch =new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            new Thread(new FirstCountDown(countDownLatch,i)).start();
        }
        System.out.println("主线程开始等待");
        countDownLatch.await();
        System.out.println("主线程等等待结束，开始");
    }

    private static void testFirstAwait() throws InterruptedException {
        CountDownLatch countDownLatch =new CountDownLatch(1);
        for (int i = 0; i < 10; i++) {
            new FirtAwait(countDownLatch,i).start();
        }
        System.out.println("=========");
        Thread.sleep(2000);
        countDownLatch.countDown();
    }

    /**
     * 类似 @see   CyclicBarrier
     */
    static class FirtAwait extends Thread{

        private CountDownLatch countDownLatch;
        private Integer id;
        public FirtAwait(CountDownLatch countDownLatch, int i){
            this.countDownLatch=countDownLatch;
            this.id=i;
        }
        @Override
        public void run() {

            try {
                System.out.println(Thread.currentThread().getName()+id+",开始等待");
                countDownLatch.await();
                System.out.println(Thread.currentThread().getName()+id+",开始执行");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    static class FirstCountDown implements Runnable{
        private CountDownLatch countDownLatch;
        private Integer id;

        public FirstCountDown(CountDownLatch countDownLatch, Integer id) {
            this.countDownLatch = countDownLatch;
            this.id = id;
        }

        @Override
        public void run() {

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(id+"执行完毕 开始--");
            countDownLatch.countDown();
        }
    }

}

